#include "lvgl_gui.h"

static const char *TAG = "lvglgui";

static spi_device_handle_t spi;
static esp_lcd_touch_handle_t tp;

static void write_command(uint8_t cmd)
{
    spi_transaction_t t;
    memset(&t, 0, sizeof(t)); // Zero out the transaction

    t.cmd = 0;
    t.addr = cmd;
    spi_device_transmit(spi, &t);
}

static void write_data(uint8_t data)
{
    spi_transaction_t t;
    memset(&t, 0, sizeof(t)); // Zero out the transaction

    t.cmd = 1;
    t.addr = data;
    spi_device_transmit(spi, &t);
}

static void lcd_rst(void)
{
    ESP_LOGI(TAG, "Turn off LCD backlight");
    gpio_config_t bk_gpio_config = {
        .mode = GPIO_MODE_OUTPUT,
        .pin_bit_mask = 1ULL << GPIO_NUM_41};
    ESP_ERROR_CHECK(gpio_config(&bk_gpio_config));

    gpio_set_level(GPIO_NUM_41, 0);
    vTaskDelay(pdMS_TO_TICKS(10));
    gpio_set_level(GPIO_NUM_41, 1);
    vTaskDelay(pdMS_TO_TICKS(500));
}

static void lcd_init_cmd(void)
{
    write_command(0xFF); // Change to Page 1 CMD
    write_data(0xFF);
    write_data(0x98);
    write_data(0x06);
    write_data(0x04);
    write_data(0x01);

    write_command(0x08); // Output    SDA
    write_data(0x10);

    write_command(0x20); // set DE/VSYNC mode
    write_data(0x00);

    write_command(0x21); // DE = 1 Active
    write_data(0x01);

    write_command(0x30); // Resolution setting 480 X 854
    write_data(0x01);

    write_command(0x31); // Inversion setting 2-dot
    write_data(0x00);

    write_command(0x40); // BT  AVDD,AVDD
    write_data(0x16);    //

    write_command(0x41);
    write_data(0x33); // 22

    write_command(0x42);
    write_data(0x03); // VGL=DDVDH+VCIP -DDVDL,VGH=2DDVDL-VCIP

    write_command(0x43);
    write_data(0x09); // SET VGH clamp level

    write_command(0x44);
    write_data(0x06); // SET VGL clamp level

    write_command(0x50); // VREG1
    write_data(0x88);

    write_command(0x51); // VREG2
    write_data(0x88);

    write_command(0x52); // Flicker MSB
    write_data(0x00);

    write_command(0x53); // Flicker LSB
    write_data(0x49);    // VCOM

    write_command(0x55); // //Flicker
    write_data(0x49);

    write_command(0x60);
    write_data(0x07);

    write_command(0x61);
    write_data(0x00);

    write_command(0x62);
    write_data(0x07);

    write_command(0x63);
    write_data(0x00);
    //++++++++++++++++++ Gamma Setting ++++++++++++++++++//
    write_command(0xA0); // Positive Gamma
    write_data(0x00);
    write_command(0xA1); //
    write_data(0x09);
    write_command(0xA2); //
    write_data(0x11);
    write_command(0xA3); //
    write_data(0x0B);
    write_command(0xA4); //
    write_data(0x05);
    write_command(0xA5); //
    write_data(0x08);
    write_command(0xA6); //
    write_data(0x06);
    write_command(0xA7); //
    write_data(0x04);
    write_command(0xA8); //
    write_data(0x09);
    write_command(0xA9); //
    write_data(0x0C);
    write_command(0xAA); //
    write_data(0x15);
    write_command(0xAB); //
    write_data(0x08);
    write_command(0xAC); //
    write_data(0x0F);
    write_command(0xAD); //
    write_data(0x12);
    write_command(0xAE); //
    write_data(0x09);
    write_command(0xAF); //
    write_data(0x00);
    ///==============Nagitive
    write_command(0xC0); // Negative Gamma
    write_data(0x00);
    write_command(0xC1); //
    write_data(0x09);
    write_command(0xC2); //
    write_data(0x10);
    write_command(0xC3); //
    write_data(0x0C);
    write_command(0xC4); //
    write_data(0x05);
    write_command(0xC5); //
    write_data(0x08);
    write_command(0xC6); //
    write_data(0x06);
    write_command(0xC7); //
    write_data(0x04);
    write_command(0xC8); //
    write_data(0x08);
    write_command(0xC9); //
    write_data(0x0C);
    write_command(0xCA); //
    write_data(0x14);
    write_command(0xCB); //
    write_data(0x08);
    write_command(0xCC); //
    write_data(0x0F);
    write_command(0xCD); //
    write_data(0x11);
    write_command(0xCE); //
    write_data(0x09);
    write_command(0xCF); //
    write_data(0x00);

    write_command(0xFF); // Change to Page 6 CMD for GIP timing
    write_data(0xFF);
    write_data(0x98);
    write_data(0x06);
    write_data(0x04);
    write_data(0x06);

    write_command(0x00); //
    write_data(0x20);
    write_command(0x01); //
    write_data(0x0A);
    write_command(0x02); //
    write_data(0x00);
    write_command(0x03); //
    write_data(0x00);
    write_command(0x04); //
    write_data(0x01);
    write_command(0x05); //
    write_data(0x01);
    write_command(0x06); //
    write_data(0x98);
    write_command(0x07); //
    write_data(0x06);
    write_command(0x08); //
    write_data(0x01);
    write_command(0x09); //
    write_data(0x80);
    write_command(0x0A); //
    write_data(0x00);
    write_command(0x0B); //
    write_data(0x00);
    write_command(0x0C); //
    write_data(0x01);
    write_command(0x0D); //
    write_data(0x01);
    write_command(0x0E); //
    write_data(0x05);
    write_command(0x0F); //
    write_data(0x00);

    write_command(0x10); //
    write_data(0xF0);
    write_command(0x11); //
    write_data(0xF4);
    write_command(0x12); //
    write_data(0x01);
    write_command(0x13); //
    write_data(0x00);
    write_command(0x14); //
    write_data(0x00);
    write_command(0x15); //
    write_data(0xC0);
    write_command(0x16); //
    write_data(0x08);
    write_command(0x17); //
    write_data(0x00);
    write_command(0x18); //
    write_data(0x00);
    write_command(0x19); //
    write_data(0x00);
    write_command(0x1A); //
    write_data(0x00);
    write_command(0x1B); //
    write_data(0x00);
    write_command(0x1C); //
    write_data(0x00);
    write_command(0x1D); //
    write_data(0x00);

    write_command(0x20); //
    write_data(0x01);
    write_command(0x21); //
    write_data(0x23);
    write_command(0x22); //
    write_data(0x45);
    write_command(0x23); //
    write_data(0x67);
    write_command(0x24); //
    write_data(0x01);
    write_command(0x25); //
    write_data(0x23);
    write_command(0x26); //
    write_data(0x45);
    write_command(0x27); //
    write_data(0x67);

    write_command(0x30); //
    write_data(0x11);
    write_command(0x31); //
    write_data(0x11);
    write_command(0x32); //
    write_data(0x00);
    write_command(0x33); //
    write_data(0xEE);
    write_command(0x34); //
    write_data(0xFF);
    write_command(0x35); //
    write_data(0xBB);
    write_command(0x36); //
    write_data(0xAA);
    write_command(0x37); //
    write_data(0xDD);
    write_command(0x38); //
    write_data(0xCC);
    write_command(0x39); //
    write_data(0x66);
    write_command(0x3A); //
    write_data(0x77);
    write_command(0x3B); //
    write_data(0x22);
    write_command(0x3C); //
    write_data(0x22);
    write_command(0x3D); //
    write_data(0x22);
    write_command(0x3E); //
    write_data(0x22);
    write_command(0x3F); //
    write_data(0x22);
    write_command(0x40); //
    write_data(0x22);

    write_command(0xFF); // Change to Page 7 CMD for GIP timing
    write_data(0xFF);
    write_data(0x98);
    write_data(0x06);
    write_data(0x04);
    write_data(0x07);

    write_command(0x17);
    write_data(0x22);

    write_command(0x02);
    write_data(0x77);

    write_command(0x26);
    write_data(0xB2);

    write_command(0xFF); // Change to Page 0 CMD for Normal command
    write_data(0xFF);
    write_data(0x98);
    write_data(0x06);
    write_data(0x04);
    write_data(0x00);

    write_command(0x3A);
    write_data(0x50); // 24BIT

    write_command(0x11);
    vTaskDelay(pdMS_TO_TICKS(120));
    write_command(0x29);
    vTaskDelay(pdMS_TO_TICKS(25));
}

static void lcd_init(void)
{
    esp_err_t ret;
    spi_bus_config_t buscfg = {
        .miso_io_num = -1,
        .mosi_io_num = PIN_NUM_MOSI,
        .sclk_io_num = PIN_NUM_CLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
    };
    spi_device_interface_config_t devcfg = {
        .command_bits = 1,
        .address_bits = 8,
        .clock_speed_hz = 10 * 1000 * 1000, // Clock out at 26 MHz
        .mode = 0,                          // SPI mode 0
        .spics_io_num = PIN_NUM_CS,         // CS pin
        .queue_size = 1,                    // We want to be able to queue 1 transactions at a time
    };
    // Initialize the SPI bus
    ret = spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO);
    ESP_ERROR_CHECK(ret);
    // Attach the LCD to the SPI bus
    ret = spi_bus_add_device(LCD_HOST, &devcfg, &spi);
    ESP_ERROR_CHECK(ret);

    lcd_init_cmd();

    spi_bus_remove_device(spi);
    // spi_bus_free(LCD_HOST);

    // gpio_set_level(PIN_NUM_CS, 1);
    // gpio_reset_pin(PIN_NUM_MOSI);
    // gpio_reset_pin(PIN_NUM_CLK);
}

static void example_lvgl_flush_cb(lv_disp_drv_t *drv, const lv_area_t *area, lv_color_t *color_map)
{
    esp_lcd_panel_handle_t panel_handle = (esp_lcd_panel_handle_t)drv->user_data;
    int offsetx1 = area->x1;
    int offsetx2 = area->x2;
    int offsety1 = area->y1;
    int offsety2 = area->y2;

    // pass the draw buffer to the driver
    esp_lcd_panel_draw_bitmap(panel_handle, offsetx1, offsety1, offsetx2 + 1, offsety2 + 1, color_map);
    lv_disp_flush_ready(drv);
}

static void example_increase_lvgl_tick(void *arg)
{
    /* Tell LVGL how many milliseconds has elapsed */
    lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
}

static void touch_init(void)
{
    ESP_LOGI(TAG, "Initialize I2C bus");
    i2c_config_t i2c_conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = 39,
        .scl_io_num = 38,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = 400 * 1000,
    };
    ESP_ERROR_CHECK(i2c_param_config(0, &i2c_conf));
    ESP_ERROR_CHECK(i2c_driver_install(0, I2C_MODE_MASTER, 0, 0, 0));

    esp_lcd_panel_io_handle_t tp_io_handle = NULL;
    esp_lcd_panel_io_i2c_config_t tp_io_config = ESP_LCD_TOUCH_IO_I2C_GT911_CONFIG();

    esp_lcd_new_panel_io_i2c(0, &tp_io_config, &tp_io_handle);

    esp_lcd_touch_config_t tp_cfg = {
        .x_max = EXAMPLE_LCD_H_RES,
        .y_max = EXAMPLE_LCD_V_RES,
        .rst_gpio_num = -1,
        .int_gpio_num = 40,
        .flags = {
            .swap_xy = 0,
            .mirror_x = 0,
            .mirror_y = 0,
        },
    };
    // vTaskDelay(pdMS_TO_TICKS(1000));
    esp_err_t err = ESP_FAIL;
    while (err != ESP_OK)
    {
        lcd_rst();
        if (tp != NULL)
        {
            esp_lcd_touch_del(tp);
        }
        esp_lcd_touch_new_i2c_gt911(tp_io_handle, &tp_cfg, &tp);
        err = esp_lcd_touch_read_data(tp);
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

static void example_lvgl_touch_cb(lv_indev_drv_t *drv, lv_indev_data_t *data)
{
    uint16_t touchpad_x[1] = {0};
    uint16_t touchpad_y[1] = {0};
    uint8_t touchpad_cnt = 0;

    /* Read touch controller data */
    esp_lcd_touch_read_data(drv->user_data);

    /* Get coordinates */
    bool touchpad_pressed = esp_lcd_touch_get_coordinates(drv->user_data, touchpad_x, touchpad_y, NULL, &touchpad_cnt, 1);

    if (touchpad_pressed && touchpad_cnt > 0)
    {
        data->point.x = touchpad_x[0];
        data->point.y = touchpad_y[0];
        data->state = LV_INDEV_STATE_PRESSED;
    }
    else
    {
        data->state = LV_INDEV_STATE_RELEASED;
    }
}

void guiTask(void *pvParameters)
{
    static lv_disp_draw_buf_t disp_buf; // contains internal graphic buffer(s) called draw buffer(s)
    static lv_disp_drv_t disp_drv;      // contains callback functions

    lcd_rst();
    touch_init();
    lcd_init();

    ESP_LOGI(TAG, "Turn off LCD backlight");
    gpio_config_t bk_gpio_config = {
        .mode = GPIO_MODE_OUTPUT,
        .pin_bit_mask = 1ULL << EXAMPLE_PIN_NUM_BK_LIGHT};
    ESP_ERROR_CHECK(gpio_config(&bk_gpio_config));
    gpio_set_level(EXAMPLE_PIN_NUM_BK_LIGHT, !EXAMPLE_LCD_BK_LIGHT_ON_LEVEL);

    ESP_LOGI(TAG, "Install RGB LCD panel driver");
    esp_lcd_panel_handle_t panel_handle = NULL;
    esp_lcd_rgb_panel_config_t panel_config = {
        .data_width = 16, // RGB565 in parallel mode, thus 16bit in width
        .psram_trans_align = 64,
        .clk_src = LCD_CLK_SRC_DEFAULT,
        .disp_gpio_num = EXAMPLE_PIN_NUM_DISP_EN,
        .pclk_gpio_num = EXAMPLE_PIN_NUM_PCLK,
        .vsync_gpio_num = EXAMPLE_PIN_NUM_VSYNC,
        .hsync_gpio_num = EXAMPLE_PIN_NUM_HSYNC,
        .de_gpio_num = EXAMPLE_PIN_NUM_DE,
        .data_gpio_nums = {
            EXAMPLE_PIN_NUM_DATA0,
            EXAMPLE_PIN_NUM_DATA1,
            EXAMPLE_PIN_NUM_DATA2,
            EXAMPLE_PIN_NUM_DATA3,
            EXAMPLE_PIN_NUM_DATA4,
            EXAMPLE_PIN_NUM_DATA5,
            EXAMPLE_PIN_NUM_DATA6,
            EXAMPLE_PIN_NUM_DATA7,
            EXAMPLE_PIN_NUM_DATA8,
            EXAMPLE_PIN_NUM_DATA9,
            EXAMPLE_PIN_NUM_DATA10,
            EXAMPLE_PIN_NUM_DATA11,
            EXAMPLE_PIN_NUM_DATA12,
            EXAMPLE_PIN_NUM_DATA13,
            EXAMPLE_PIN_NUM_DATA14,
            EXAMPLE_PIN_NUM_DATA15,
        },
        .timings = {
            .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ,
            .h_res = EXAMPLE_LCD_H_RES,
            .v_res = EXAMPLE_LCD_V_RES,
            // The following parameters should refer to LCD spec
            .hsync_back_porch = 30,
            .hsync_front_porch = 18,
            .hsync_pulse_width = 4,
            .vsync_back_porch = 30,
            .vsync_front_porch = 20,
            .vsync_pulse_width = 4,
            .flags.pclk_active_neg = false,
        },
        .flags.fb_in_psram = true, // allocate frame buffer in PSRAM
        // .flags.double_fb = true,
    };
    ESP_ERROR_CHECK(esp_lcd_new_rgb_panel(&panel_config, &panel_handle));

    ESP_LOGI(TAG, "Initialize RGB LCD panel");
    ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_handle));
    ESP_ERROR_CHECK(esp_lcd_panel_init(panel_handle));

    ESP_LOGI(TAG, "Initialize LVGL library");
    lv_init();
    void *buf1 = NULL;
    void *buf2 = NULL;
    ESP_LOGI(TAG, "Allocate separate LVGL draw buffers from PSRAM");
    // buf1 = heap_caps_malloc(EXAMPLE_LCD_H_RES * 854 * sizeof(lv_color_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
    buf1 = heap_caps_malloc(EXAMPLE_LCD_H_RES * 50 * sizeof(lv_color_t), MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
    assert(buf1);
    // buf2 = heap_caps_malloc(EXAMPLE_LCD_H_RES * 854 * sizeof(lv_color_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
    buf2 = heap_caps_malloc(EXAMPLE_LCD_H_RES * 50 * sizeof(lv_color_t), MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
    assert(buf2);
    // initialize LVGL draw buffers
    lv_disp_draw_buf_init(&disp_buf, buf1, buf2, EXAMPLE_LCD_H_RES * 50);

    // ESP_LOGI(TAG, "Use frame buffers as LVGL draw buffers");
    // ESP_ERROR_CHECK(esp_lcd_rgb_panel_get_frame_buffer(panel_handle, 2, &buf1, &buf2));
    // // initialize LVGL draw buffers
    // lv_disp_draw_buf_init(&disp_buf, buf1, buf2, EXAMPLE_LCD_H_RES * EXAMPLE_LCD_V_RES);

    ESP_LOGI(TAG, "Register display driver to LVGL");
    lv_disp_drv_init(&disp_drv);
    disp_drv.hor_res = EXAMPLE_LCD_H_RES;
    disp_drv.ver_res = EXAMPLE_LCD_V_RES;
    disp_drv.flush_cb = example_lvgl_flush_cb;
    disp_drv.draw_buf = &disp_buf;
    disp_drv.user_data = panel_handle;

    lv_disp_t *disp = lv_disp_drv_register(&disp_drv);

    ESP_LOGI(TAG, "Install LVGL tick timer");
    // Tick interface for LVGL (using esp_timer to generate 2ms periodic event)
    const esp_timer_create_args_t lvgl_tick_timer_args = {
        .callback = &example_increase_lvgl_tick,
        .name = "lvgl_tick"};
    esp_timer_handle_t lvgl_tick_timer = NULL;
    ESP_ERROR_CHECK(esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer));
    ESP_ERROR_CHECK(esp_timer_start_periodic(lvgl_tick_timer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000));

    static lv_indev_drv_t indev_drv; // Input device driver (Touch)
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.disp = disp;
    indev_drv.read_cb = example_lvgl_touch_cb;
    indev_drv.user_data = tp;

    lv_indev_drv_register(&indev_drv);

    ESP_LOGI(TAG, "Turn on LCD backlight");
    gpio_set_level(EXAMPLE_PIN_NUM_BK_LIGHT, EXAMPLE_LCD_BK_LIGHT_ON_LEVEL);

    ESP_LOGI(TAG, "Display LVGL Scatter Chart");
    // example_lvgl_demo_ui(disp);
    // lv_demo_benchmark_set_max_speed(true);
    // lv_demo_benchmark();

    // lv_demo_music();
    // lv_demo_widgets();

    // create_demo_app();

    while (1)
    {
        // raise the task priority of LVGL and/or reduce the handler period can improve the performance
        vTaskDelay(pdMS_TO_TICKS(10));
        // The task running lv_timer_handler should have lower priority than that running `lv_tick_inc`
        lv_timer_handler();
    }
}